Option Strict Off
Option Explicit On

Imports System.IO

Namespace SDIFChecker

    Public Module Create
        'global object variables
        Public gwsMainWS As dao.Workspace ' Main workspace object
        Public dbsNew As dao.Database

        Function Create_SDF_File(ByRef tFile As String) As String
            Dim FileNumber, FileNumber2 As Short
            Dim tSDIF_type As String
            Dim X, I, P As Short
            Dim tOut, tField As String
            Dim tStr As String = ""

            Create_SDF_File = ""
            SDIFChecker.SetHourglass()

            Try
                I = LoadSDIFDDL(gsVersion)

                If I = -1 Then
                    SDIFChecker.UnSetHourglass()
                    tStr = "Error: """ & gsVersion & """ definition file not found!" & vbCrLf & vbCrLf
                    tStr = tStr & "This file must be in """ & My.Application.Info.DirectoryPath & """ in order to import " & vbCrLf
                    tStr = tStr & "successfully."
                    MsgBox(tStr, MsgBoxStyle.Critical)
                    Exit Function
                ElseIf I > 1 Then
                    SDIFChecker.UnSetHourglass()
                    tStr = "Error: """ & gsVersion & """ definition file is corrupted!" & vbCrLf & vbCrLf
                    tStr = tStr & "This file has a format error on that needs correcting!" & vbCrLf
                    tStr = tStr & vbCrLf & "Line(" & CStr(I) & ")=" & gsString
                    MsgBox(tStr, MsgBoxStyle.Critical)
                    Exit Function
                End If

                tStr = Path.ChangeExtension(tFile, "csv")
                If File.Exists(tStr) = True Then
                    If MsgBox("""" & tStr & """ already exists!" & vbCrLf & vbCrLf & "Delete first?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                        Kill(tStr)
                    Else
                        Exit Function
                    End If
                End If
            Catch ex As Exception
                MsgBox("Error loading " & gsVersion & " : Error : " & ex.Message)
            End Try

            Try
                FileNumber = FreeFile()
                FileOpen(FileNumber, tFile, OpenMode.Input)

                FileNumber2 = FreeFile()
                FileOpen(FileNumber2, tStr, OpenMode.Output)
                Create_SDF_File = tStr

                P = 0
                Do While Not EOF(FileNumber)
                    'Read record
                    tStr = LineInput(FileNumber)
                    tSDIF_type = Left(tStr, 2)
                    tOut = ""
                    For I = 0 To UBound(gsType) - 1
                        If tSDIF_type = gsType(I) Then
                            X = 0
                            While giStart(I, X) <> 0
                                tField = GetSDIF(tStr, giStart(I, X), giLength(I, X))
                                If X <> 0 Then
                                    tOut = tOut & ","
                                End If
                                If gsFType(I, X) = "INT" Then
                                    tOut = tOut & tField
                                Else
                                    tOut = tOut & """" & tField & """"
                                End If
                                X = X + 1
                            End While
                            PrintLine(FileNumber2, tOut)
                        End If
                    Next I
                    P = P + 1
                Loop

                FileClose(FileNumber)
                FileClose(FileNumber2)
            Catch ex As Exception
                MsgBox("Error creating " & Path.ChangeExtension(tFile, "csv") & " : Error : " & ex.Message)
            End Try

            SDIFChecker.UnSetHourglass()
        End Function


        Function Load_Database(ByRef mdbFile As String) As String
            Dim FileNumber As Short
            Dim tSDIF_type As String
            Dim savType As String = ""
            Dim P As Short
            Dim MyTable As DAO.Recordset
            Dim bInsert As Boolean
            Dim fldloop As dao.Field
            Dim tStr, tField As String

            Load_Database = ""
            SDIFChecker.SetHourglass()
            FileNumber = FreeFile()

            Try
                FileOpen(FileNumber, gsSDIFName, OpenMode.Input)
                dbsNew = gwsMainWS.OpenDatabase(mdbFile)

                P = 0
                Do While Not EOF(FileNumber)

                    tStr = LineInput(FileNumber)
                    tSDIF_type = Left(tStr, 2)

                    Try
                        If savType <> tSDIF_type Then
                            If savType <> "" Then
                                MyTable.Close()
                            End If
                            MyTable = dbsNew.OpenRecordset(tSDIF_type & "_Record", dao.RecordsetTypeEnum.dbOpenTable)
                            savType = tSDIF_type
                        End If
                    Catch ex As Exception
                        savType = ""
                    End Try

                    Try
                        If savType = tSDIF_type Then
                            bInsert = False
                            For Each fldloop In MyTable.Fields
                                tField = GetSDIFField((fldloop.Name), tSDIF_type, tStr)
                                If tField <> "" Then
                                    If bInsert = False Then
                                        MyTable.AddNew()
                                        bInsert = True
                                    End If
                                    fldloop.Value = tField
                                End If
                            Next fldloop
                            If bInsert = True Then
                                MyTable.Update()
                            End If
                        End If
                    Catch ex As Exception
                        MsgBox(String.Format("Error adding data to {0} : Error : {1}", mdbFile, ex.Message))
                    End Try

                    P = P + 1
                    frmMain.ProgressBar1.Value = P
                    System.Windows.Forms.Application.DoEvents()
                Loop

                If savType <> "" Then
                    MyTable.Close()
                End If

            Catch ex As Exception
                MsgBox(String.Format("Error opening {0} : Error : {1}", mdbFile, ex.Message))
            Finally
                dbsNew.Close()
                FileClose(FileNumber)
            End Try

            SDIFChecker.UnSetHourglass()
            frmMain.ProgressBar1.Value = 0

        End Function


        Function Create_Database(ByRef tFile As String) As String
            Dim tStr As String
            Dim I, X As Short

            Create_Database = Path.ChangeExtension(tFile, "mdb")

            SDIFChecker.SetHourglass()
            I = LoadSDIFDDL(gsVersion)
            If I = -1 Then
                SDIFChecker.UnSetHourglass()
                tStr = "Error: """ & gsVersion & """ definition file not found!" & vbCrLf & vbCrLf
                tStr = tStr & "This file must be in """ & My.Application.Info.DirectoryPath & """ in order to import " & vbCrLf
                tStr = tStr & "successfully."
                MsgBox(tStr, MsgBoxStyle.Critical)
                Exit Function
            ElseIf I > 1 Then
                SDIFChecker.UnSetHourglass()
                tStr = "Error: """ & gsVersion & """ definition file is corrupted!" & vbCrLf & vbCrLf
                tStr = tStr & "This file has a format error on that needs correcting!" & vbCrLf
                tStr = tStr & vbCrLf & "Line(" & CStr(I) & ")=" & gsString
                MsgBox(tStr, MsgBoxStyle.Critical)
                Exit Function
            End If

            Dim savType As String = ""
            Dim savAttribute As String = ""
            Dim bError As Boolean = False

            If File.Exists(Create_Database) = True Then
                If MsgBox("""" & Create_Database & """ already exists!" & vbCrLf & vbCrLf & "Delete first?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                    File.Delete(Create_Database)
                Else
                    Exit Function
                End If
            End If

            Try
                DAODBEngine_definst.DefaultUser = "admin"
                DAODBEngine_definst.DefaultPassword = ""

                gwsMainWS = DAODBEngine_definst.CreateWorkspace("MainWS", "admin", "")
                DAODBEngine_definst.Workspaces.Append(gwsMainWS)

                dbsNew = gwsMainWS.CreateDatabase(Create_Database, dao.LanguageConstants.dbLangGeneral)

                Dim td As dao.TableDef
                Dim f As Short = 0

                For I = 0 To UBound(gsType) - 1
                    If savType <> gsType(I) Then
                        If savType <> "" And f > 0 Then
                            dbsNew.TableDefs.Append(td)
                            'MsgBox("append " & savType)
                            savType = ""
                            f = 0
                        End If
                        td = dbsNew.CreateTableDef(gsType(I) & "_Record")
                        ' MsgBox("Create " & gsType(I) & " table")
                        savType = gsType(I)
                    End If
                    X = 0
                    While giStart(I, X) <> 0
                        If UCase(gsFType(I, X)) = "CONST" Then
                            X = X + 1
                        ElseIf UCase(gsVariable(I, X)) = "FUTURE USE" Then
                            X = X + 1
                        ElseIf Len(gsAttribute(I, X)) > 0 Then
                            Debug.Print("Add " & gsAttribute(I, X) & " to " & gsType(I))
                            savAttribute = gsAttribute(I, X)
                            Dim fd As dao.Field = td.CreateField(savAttribute, dbText, giLength(I, X))
                            fd.DefaultValue = ""
                            fd.AllowZeroLength = True
                            td.Fields.Append(fd)
                            f = f + 1
                            X = X + 1
                        Else
                            X = X + 1
                        End If
                    End While
                Next I

                If savType <> "" And f > 0 Then
                    dbsNew.TableDefs.Append(td)
                End If

            Catch ex As Exception
                bError = True
                MsgBox(String.Format("Error creating {0} schema\nError: {1} on the {2}/{3} record.", _
                    tFile, ex.Message, savType, savAttribute), MsgBoxStyle.Critical)
            Finally
                dbsNew.Close()
            End Try

            If bError = True Then
                File.Delete(Create_Database)
                Create_Database = ""
            End If

            SDIFChecker.UnSetHourglass()

        End Function
    End Module
End Namespace
